package com.ruiben.mall.controller;


import com.ruiben.mall.impl.AttributeServiceImpl;
import com.ruiben.mall.pojo.Attribute;
import com.ruiben.mall.utils.CommonJSONResult;
import com.ruiben.mall.utils.PagedResult;
import com.ruiben.mall.vo.AttributeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static com.ruiben.mall.config.ErrorConfig.*;
import static com.ruiben.mall.controller.BaseController.PAGE_SIZE;

@RequestMapping("attr")
@RestController
public class AttributeController {

    @Autowired
    private AttributeServiceImpl attributeService;

    /**
     * 根据类型id来获取当前属性列表
     *
     * @param page
     * @param typeId
     */
    @PostMapping("getAttributeList")
    public CommonJSONResult getAttributeListForTypeId(Integer page, String typeId) {

        if (StringUtils.isBlank(typeId)) {
            return CommonJSONResult.build(ID_NOT_EMPTY_CODE, ID_NOT_EMPTY_MSG, null);
        }

        if (page == null) {
            page = 1;
        }


        PagedResult pagedResult = attributeService.getAttributeList(page, PAGE_SIZE, typeId);
        return CommonJSONResult.ok(pagedResult);

    }


    @PostMapping("getAllAttrList")
    public CommonJSONResult getAttributeListForTypeId(String typeId) {

        if (StringUtils.isBlank(typeId)) {
            return CommonJSONResult.build(ID_NOT_EMPTY_CODE, ID_NOT_EMPTY_MSG, null);
        }


        List<Attribute> attributeList = attributeService.getAttributeList(typeId,0);

        List<AttributeVo> attributeVos = new ArrayList<>();
        for (Attribute attribute : attributeList){
            AttributeVo attributeVo = new AttributeVo();
            BeanUtils.copyProperties(attribute,attributeVo);
            attributeVo.setValueStr("");
            attributeVos.add(attributeVo);
        }

        if (attributeVos.size() > 0) {

            return CommonJSONResult.ok(attributeVos);
        } else {
            return CommonJSONResult.errorMsg("没有数据");
        }

    }

}
